import os
import sys

# 添加Django项目路径到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 设置Django环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')

# 导入Django设置
import django
django.setup()

from django.db import connection, transaction
from django.db.migrations.recorder import MigrationRecorder

print("===== 修复inventory模块迁移状态 ======")
print("1. 查询当前inventory模块的迁移记录")

# 查询迁移记录
migrations = MigrationRecorder.Migration.objects.filter(app='inventory').order_by('applied')
if migrations:
    print(f"找到 {migrations.count()} 条inventory模块的迁移记录：")
    for m in migrations:
        print(f"  - 迁移名称：{m.name}，应用时间：{m.applied}")
        
    # 确认是否删除
    print("\n2. 准备删除这些迁移记录")
    try:
        with transaction.atomic():
            # 删除迁移记录
            deleted_count, _ = MigrationRecorder.Migration.objects.filter(app='inventory').delete()
            print(f"成功删除 {deleted_count} 条迁移记录")
            
            # 输出删除后的状态
            remaining_migrations = MigrationRecorder.Migration.objects.filter(app='inventory').count()
            print(f"删除后剩余的inventory迁移记录数：{remaining_migrations}")
            
    except Exception as e:
        print(f"删除迁移记录失败：{e}")
else:
    print("没有找到inventory模块的迁移记录")

print("\n===== 修复完成 ======")
print("现在可以运行 'python manage.py migrate inventory' 来重新创建表")